from PyQt5.QtCore import QTimer, Qt, QCoreApplication
from PyQt5.QtWidgets import QApplication, QWidget, QAction, QMenu, QSystemTrayIcon, QMessageBox
from PyQt5.QtGui import QPainter, QBrush, QColor, QPen, QIcon

import utils
from log import LOGGER

ONE_MINUTE = 60 * 1000
WORK_SPAN = 25 * ONE_MINUTE
REST_SPAN = 4 * ONE_MINUTE


class ScreenLocker(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
        screen = QApplication.primaryScreen()
        self.screen_geo = screen.geometry()
        self.setGeometry(self.screen_geo)

        self.set_system_tray()

        self.work_timer = QTimer(self)
        self.work_timer.timeout.connect(self.lock_screen)

        self.rest_timer = QTimer(self)
        self.rest_timer.timeout.connect(self.unlock_screen)

        self.work_timer.start(WORK_SPAN)

        self.disp_timer = QTimer(self)
        self.disp_timer.timeout.connect(self.disp)
        self.disp_timer.start(5000)

    def disp(self):
        if self.isHidden():
            LOGGER.info("already work for %s, remaining %s to rest" % (
                self.elapse_disp((WORK_SPAN - self.work_timer.remainingTime()) / 1000),
                self.elapse_disp(self.work_timer.remainingTime() / 1000),
            ))
        else:
            LOGGER.info("rest time left:%s" % (self.elapse_disp(self.rest_timer.remainingTime() / 1000)))

    def set_system_tray(self):
        self.quit_action = QAction("exit", self)
        self.quit_action.setIcon(QIcon.fromTheme("application-exit"))
        self.quit_action.triggered.connect(self.quit_app)

        self.open_action = QAction("hint", self)
        self.open_action.setIcon(QIcon.fromTheme("document-open"))
        self.open_action.triggered.connect(self.show_app)

        self.tray_icon_menu = QMenu(self)
        self.tray_icon_menu.addAction(self.open_action)
        self.tray_icon_menu.addAction(self.quit_action)

        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setContextMenu(self.tray_icon_menu)
        self.tray_icon.setIcon(QIcon.fromTheme("system-help"))
        self.tray_icon.setToolTip("eye protector")
        self.tray_icon.show()
        LOGGER.info("set_system_tray complete")

    def show_app(self):
        if self.isHidden():
            QMessageBox.information(self, 'info', "already work for %s, remaining %s to rest" % (
                self.elapse_disp((WORK_SPAN - self.work_timer.remainingTime()) / 1000),
                self.elapse_disp(self.work_timer.remainingTime() / 1000),
            ))

    @staticmethod
    def elapse_disp(secs):
        min = secs / 60
        remainder = secs % 60
        return '%d minutes %d seconds' % (min, remainder)

    def quit_app(self):
        QCoreApplication.quit()
        LOGGER.info("app exit!")

    def lock_screen(self):
        LOGGER.info('lock_screen')
        self.show()

        self.work_timer.stop()
        self.rest_timer.start(REST_SPAN)

    def unlock_screen(self):
        LOGGER.info('unlock_screen')
        self.hide()

        self.rest_timer.stop()
        self.work_timer.start(WORK_SPAN)

    def closeEvent(self, event):
        self.rest_timer.stop()
        self.work_timer.stop()
        event.accept()
        LOGGER.info("window closed")

    def paintEvent(self, evt):
        painter = QPainter(self)
        painter.save()
        painter.setBrush(QBrush(QColor(0, 0, 0)))
        painter.drawRect(self.screen_geo)
        painter.restore()

        painter.save()
        font = self.font()
        font.setPointSize(20)
        painter.setFont(font)
        painter.setPen(QPen(QColor(255, 255, 255)))
        painter.drawText(self.screen_geo, Qt.AlignCenter | Qt.TextWordWrap, "please have a rest")
        painter.restore()
        painter.end()


def main():
    import sys
    app = QApplication(sys.argv)

    procs = utils.find_process_by_cmd('eye_protector.py')
    if len(procs) >= 2:
        LOGGER.warning("other procs exist:%s" % (procs))
        QMessageBox.critical(None, 'error', 'another eye protector already started!')
        sys.exit(-1)

    QMessageBox.information(None, 'info', 'eye protector started success')
    widget = ScreenLocker()
    widget.hide()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
